package net.homeip.mmhg.util;

import org.quartz.Job;
import org.quartz.SchedulerException;
import org.quartz.simpl.SimpleJobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class CustomJobFactory extends SimpleJobFactory implements ApplicationContextAware {

	private ApplicationContext context;
	
	@Override
	public Job newJob(TriggerFiredBundle bundle) throws SchedulerException {
		String[] beanNames = context.getBeanNamesForType(bundle.getJobDetail().getJobClass());
		if ( (beanNames == null) || (beanNames.length == 0) ) {
			return super.newJob(bundle);
		} else {
			return (Job) context.getBean(beanNames[0]);
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
	}

}
